package com.kang.mavenweb.dao;


import com.kang.mavenweb.domain.Book;
import com.kang.mavenweb.domain.User;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class BookDaoImpl extends HibernateDaoSupport implements IBookDao {
/////
    @Autowired
    private void setSuperSessionFactory(SessionFactory superSessionFactory){
        super.setSessionFactory (superSessionFactory);
    }

    @Transactional
    @Override
    public void add(Book book, User user) {
        this.getHibernateTemplate ( ).save ( user);
    }

    @Transactional
    @Override
    public List<Book> findByUser(int id) {
        Session currentSession = this.getSessionFactory ( ).getCurrentSession ( );
        SQLQuery sqlQuery = currentSession.createSQLQuery ("SELECT *FROM t_book LEFT JOIN t_book_t_user tbtu ON t_book.id = tbtu.bs_id WHERE tbtu.us_id = ?").addEntity (Book.class);
        sqlQuery.setParameter (0, id);
        return sqlQuery.list ();
        ////
    }
}
